package com.wang.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wang.pojo.Dept;
import com.wang.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: along
 * @Create: 2021/6/5
 * @Description:
 */
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private DiscoveryClient client;

    @RequestMapping("/dept/add")
    public boolean addDept(Dept dept) {
        return deptService.addDept(dept);
    }

    @RequestMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet")
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = deptService.queryById(id);

        if(dept == null) {
            throw new RuntimeException("id==>" + id + "不存在该用户，或者信息无法找到");
        }
        return dept;
    }


    public Dept hystrixGet(@PathVariable("id") Long id) {
        return new Dept()
                .setDno(id)
                .setDname("id==>" + id + "不存在该用户，或者信息无法找到")
                .setDb_source("no such database in MySQL");
    }

    @RequestMapping("/dept/list")
    public List<Dept> getAll() {
        return deptService.queryAll();
    }

    @RequestMapping("/dept/discovery")
    public Object discovery() {
        List<String> services = client.getServices();
        System.out.println("discovery==>services" + services);
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER");
        for (ServiceInstance instance : instances) {
            System.out.println(
                            instance.getHost() + "\t" +
                            instance.getPort() + "\t" +
                            instance.getUri() + "\t" +
                            instance.getServiceId() + "\t"
            );
        }
        return this.client;
    }

}
